package com.liukai.todo_android.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.liukai.todo_android.R;
import com.liukai.todo_android.call_back.IFindUserCallBack;
import com.liukai.todo_android.common.utils.Constants;
import com.liukai.todo_android.common.base.BaseActivity;
import com.liukai.todo_android.common.utils.JSONUtil;
import com.liukai.todo_android.common.utils.LogUtils;
import com.liukai.todo_android.common.utils.SharedPreferencesUtil;
import com.liukai.todo_android.entity.Resp;
import com.liukai.todo_android.entity.vo.UserVO;
import com.liukai.todo_android.presenter.FindUserPresenter;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;

/**
 * @author ：liukai
 * @date ：Created in 2021/8/8 4:24 下午
 * @description：启动时的动画界面，用于初始化一些数据
 * @modified By：
 * @version: $
 */
public class SplashActivity extends BaseActivity implements IFindUserCallBack {

    @BindView(R.id.avi)
    AVLoadingIndicatorView mIndicatorView;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};
    private FindUserPresenter findUserPresenter;
    private Context context;


    /**
     * 检查并且获取权限
     *
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected int getLayoutId() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.activity_splash;
    }

    @Override
    protected void initData(Context _context) {
        verifyStoragePermissions(this);
        // 动画界面获取本地存储的token，token不存在直接跳转至登陆界面
        String token = Constants.getToken(getApplicationContext());
        if (token == null || token.equals("")) {
            loading();
            return;
        }
        Constants.TOKEN = token;
        findUserPresenter = new FindUserPresenter();
        findUserPresenter.registerCallback(this);
        findUserPresenter.findUserInfo();
        context = _context;
    }

    @Override
    protected void initView() {
        mIndicatorView.show();
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void release() {
        super.release();
        mIndicatorView.hide();
    }


    private void loading() {
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                finish();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 错误的登录或者未登录
     *
     * @param msg
     */
    private void loginError(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        startActivity(new Intent(getApplicationContext(), LoginActivity.class));
        finish();
    }

    @Override
    public void findUserSuccess(Resp resp) {
        LogUtils.e(getClass(), resp.toString());
        if (resp.getCode() == 200) {
            UserVO userVO = JSONUtil.resolverResult(resp, UserVO.class);
            SharedPreferencesUtil.setLong(getApplicationContext(), Constants.SHARE_NAME_USER,
                    Constants.USER_ID_KEY, userVO.getId());
            startActivity(new Intent(getApplicationContext(), MainActivity.class));
            finish();
        } else {
            loginError(resp.getMessage());
        }
    }

    @Override
    public void findUserError(Resp resp) {
        loginError(resp.getMessage());
        LogUtils.e(getClass(), resp.toString());
    }

}
